﻿from simcell.genetic.protein import Protein

class ProteinBag:
    """Protein Bag"""
  
    def __init__(self):
        self.bag = {}
        self.total = 0
        self.weight = 0
        # self.volume = 0 
    
    def extractRandomProtein(self):
        if self.total > 0:            
            i = random.randint(0, self.total-1)
            acum = 0
            for protein, num in self.bag.values():
                acum += num
                if i < acum:
                    return self.extract(protein)
        return None
    
    def buildKey(self, protein):
        return "".join(map(str, protein.strand))
        
    def insert(self, protein):
        self.insertN(protein, 1)
  
    def insertN(self, protein, n):
        # self.volume += n * len(proteina)
        protein_key = self.buildKey(protein)        
        if self.bag.has_key(protein_key):
            protein, num = self.bag[protein_key]
            protein_data = (protein, num + n)
            self.bag[protein_key] = protein_data            
        else:
            self.bag[protein_key] = (protein, 1)
        
        self.total += n
        self.weight += n * len(protein.strand)
  
    def extractN(self, protein, n):
        protein_key = self.buildKey(protein)    
        n_real = min(n, self.getAmountOfprotein(protein_key))
        if n_real > 0:
            protein, num = self.bag[protein_key]
            self.bag[protein_key] = (protein, num - n_real)
            proteins = [protein for _ in range(n_real)]
            
            self.total -= n_real
            self.weight -= n_real * len(protein.aminoacids)
            
            return proteins
        else:
            return []
        # self.volume -= len(protein)
    
    def extract(self, protein):
        proteins = self.extractN(protein, 1)
        if len(proteins) > 0:
            return proteins[0]
        else:
            return None
        
    def getAmountOfprotein(self, protein_key):
        # protein_key = self.buildKey(protein)
        if self.bag.has_key(protein_key):            
            return self.bag[protein_key][1]
        else:
            return 0  
  
    # def getVolume(self):
        # """ devuelve el volumen de la bolsa"""
        # return self.volume
    def __str__(self):
        repr = "types:%d total:%d weight:%d" % (len(self.bag), self.total, self.weight)
        return repr
        
    def __repr__(self):
        repr = str(self)
        repr += "\n" + "\n".join(map(lambda x: str(self.bag[x][1]) + ' ' + str(x), self.bag))
        return repr